package cn.ycc1.my.agent.controller;

import cn.ycc1.my.agent.service.StreamingService;
import dev.langchain4j.model.chat.ChatLanguageModel;
import dev.langchain4j.model.chat.StreamingChatLanguageModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

/**
 * langchain4j
 * @author ycc
 * @date 2025/3/1
 */
@RestController
@RequestMapping("/langchain")
public class LangChainController {
    private final StreamingService streamingService;

    public LangChainController(StreamingService streamingService) {
        this.streamingService = streamingService;
    }

//    @Autowired
//    ChatLanguageModel model;

    @Autowired
    StreamingChatLanguageModel streamingChatModel;

//    @RequestMapping("/hello")
//    public String hello(){
//        String responseText = model.generate("你是谁？");
//        System.out.println(responseText);
//        return responseText;
//    }

    /**
     * 流式返回
     * @return
     */
    @GetMapping(value = "/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> streamResponse(@RequestParam String prompt) {
        return streamingService.streamResponse(prompt);
    }

    /**
     * 流式终止控制
     * @param streamId
     */
    @GetMapping("/cancel")
    public void cancelStream(@RequestParam String streamId) {
        // 实现流的中断逻辑
    }

    // 前端页面（index.html）
//    <!DOCTYPE html>
//    <html>
//    <head>
//        <title>LangChain4j Stream Demo</title>
//        </head>
//        <body>
//            <input type="text" id="prompt" placeholder="输入问题...">
//            <button onclick="startStream()">开始流式问答</button>
//            <div id="output" style="margin-top: 20px; white-space: pre-wrap;"></div>
//
//            <script>
//            function startStream() {
//                    const prompt = document.getElementById('prompt').value;
//                    const outputDiv = document.getElementById('output');
//                outputDiv.innerHTML = '';
//
//                    const eventSource = new EventSource(`http://localhost:8080/stream?prompt=${encodeURIComponent(prompt)}`);
//
//                eventSource.onmessage = (event) => {
//                    outputDiv.innerHTML += event.data;
//                    // 自动滚动到底部
//                    outputDiv.scrollTop = outputDiv.scrollHeight;
//                };
//
//                eventSource.onerror = (err) => {
//                    console.error('Stream error:', err);
//                    eventSource.close();
//                };
//            }
//            </script>
//        </body>
//    </html>

}
